import React, {
    PureComponent
} from 'react';

import {
    Text,
    View,
    Image,
    StyleSheet
} from 'react-native';

import {
    Actions
} from 'react-native-router-flux';

import moment from 'moment';

import {
    Tip,
    Button,
    Arrow,
    Layout,
    Loading
} from './../../components';

import {
    LocationData
} from './../../types/types';

import OPTIONS from './../../const/options';
import connect from './../../utils/connect';
import Select from './../home/filter/select';
import userAction from './../../state/actions/user';
import * as userTypes from './../../state/types/user';
import DatePicker from '@react-native-community/datetimepicker';

import location_icon from './../../images/location/location.png';
import location_icon_light from './../../images/location/location_light.png';


interface Props {
    user: any,
    userActions: any
}

interface State {
    genderVal: number |any,
    birthdayVal: number | any,
    locationVal: LocationData|any
}

const maxDate = (() => {
    const time = Date.now() - 1000 * 60 * 60 * 24 * 30 * 12 * 19;
    return new Date(time);
})()

const nativeVal = (a: any, b: any) => {
    return a !== undefined ? a : b;
}

@connect([`user`], {
    userActions: userAction
})
class Basic extends PureComponent<Props, State> {
    state = {
        genderVal: undefined,
        birthdayVal: undefined,
        locationVal: undefined
    }

    get userActions() {
        const {
            userActions
        } = this.props;
        return userActions;
    }

    get userState() {
        const {
            user
        } = this.props
        return user;
    }

    get userInfo() {
        const {
            loginUser
        } = this.userState;
        return loginUser;
    }

    get gender() {
        const {
            gender
        } = this.userInfo;

        const {
            id = 0
        } = gender || {};

        const {
            genderVal
        } = this.state;
        return nativeVal(genderVal,id);
    }

    get birthday() {
        const {
            birthday
        } = this.userInfo;

        const {
            birthdayVal
        } = this.state;
        return nativeVal(birthdayVal,birthday);
    }

    get locationVal() {
        const {
            location
        } = this.userInfo;
        const {
            locationVal
        } = this.state;
        return nativeVal(locationVal,location);
    }

    get birthdayName() {
        const format = `MMM DD, YYYY`;
        return this.birthday ? moment(
            this.birthday).format(format) : ``;
    }

    get locationName() {
        const {
            city = {},
            state = {},
            country = {}
        } = this.locationVal;
        return [
            city.label,
            state.label,
            country.label
        ].filter(v => !!v).join(`/`)
    }

    get disabled() {
        return !Object.values(
            this.state).filter(v=>!!v).length;
    }

    private onSubmit = async () => {
       const {
           genderVal,
           birthdayVal,
           locationVal
       }  = this.state;

       const para:any = {};

       if(!!genderVal) {
           para.gender = genderVal;
       }

       if(!!birthdayVal) {
           para.birthday = (
               moment(birthdayVal).format(
                   `YYYY-MM-DD`
               )
           )
       }

       if(!!locationVal) {
           const {
               city,
               state,
               country
           } = locationVal || {} as LocationData;

           const {
               id:cityId
           } = city || {} as any;

           const {
               id:stateId
           } = state || {} as any;

           const {
               id:countryId
           } = country || {} as any;

           para.cityId = cityId;
           para.stateId = stateId;
           para.countryId = countryId;
       }

       Loading.show();

       try {
           await this.userActions[
               userTypes.setUserProfile
           ](para);
           this.onSuccess();
       }
       catch (e) {
           Tip.warm({
               message:e.message
           })
       }

       Loading.close();
    }

    private onSuccess = () => {
        Actions.pop();
        Tip.success({
            message:`Save successfully.`
        })
    }

    private onGenderChange = (val: number) => {
        this.setState({
            genderVal: val
        })
    }

    private openLocation = () => {
        Actions.push(`/location`,{
            showAll:false,
            showHot:false,
            switchModal:true,
            onChange:this._onLocationChange
        })
    }

    private _onLocationChange = (location:any) => {
        this.setState({
            locationVal:location
        })
    }

    private openBirthday = () => {
        DatePicker({
            mode:`date`,
            display:`spinner`,
            value:this.birthday,
            maximumDate:maxDate,
            onChange:this.onDateChange
        })
    }

    private onDateChange = (res:any) => {
        const {
            type,
            nativeEvent
        } = res;
        if (type === `set`) {
            const {
                timestamp
            } = nativeEvent;
            this.setState({
                birthdayVal:timestamp
            })
        }
    }

    private renderIcon = (icon:any,light:any) => (
        (value:string) => (
            <Image
                style={styles.iconStyle}
                source={!!value?light:icon}
            />
        )
    )

    render() {
        return (
            <Layout title="My basic info" padding={false}>
                <View style={styles.rowItem}>
                    <Arrow
                        title="Date of birth"
                        value={this.birthdayName}
                        onPress={this.openBirthday}
                        titleStyle={styles.titleStyle}
                    />
                </View>
                <View style={styles.rowItem}>
                    <Text style={styles.title}>
                        Gender
                    </Text>
                    <View style={styles.content}>
                        <Select
                            value={this.gender}
                            options={OPTIONS.gender}
                            onChange={this.onGenderChange}
                        />
                    </View>
                </View>
                <View style={styles.rowItem}>
                    <Arrow
                        title="My Location"
                        value={this.locationName}
                        onPress={this.openLocation}
                        titleStyle={styles.titleStyle}
                        renderLeft={this.renderIcon(location_icon,location_icon_light)}
                    />
                </View>
                <View style={styles.buttonStyle}>
                    <Button
                        title="Save"
                        disabled={this.disabled}
                        onPress={this.onSubmit}
                    />
                </View>
            </Layout>
        )
    }
}

export default Basic;

const styles = StyleSheet.create({
    rowItem:{
        marginBottom:12,
        backgroundColor:`#323541`
    },
    title:{
        fontSize:14,
        color:`#61677C`,
        paddingTop:14,
        paddingBottom:8,
        paddingHorizontal:16
    },
    content:{
        paddingHorizontal:16
    },
    iconStyle:{
        width:20,
        height:20,
        marginRight:8
    },
    buttonStyle:{
        paddingVertical:24,
        paddingHorizontal:16
    }
}) as any;